package org.com.gamemall.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import org.com.gamemall.Entity.Community;
import org.com.gamemall.Entity.User;
import org.com.gamemall.Service.ICommunityService;
import org.com.gamemall.Service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/community")
public class CommunityController {
    @Autowired
    private IUserService userService;
    @Autowired
    private ICommunityService communityService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/publish")
    public Community publishCommunity(@RequestBody Community community, HttpServletRequest request) {
        community.setUserId(Long.valueOf(stringRedisTemplate.opsForValue().get("login:user:")));
        community.setCreateTime(LocalDateTime.now());
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId, stringRedisTemplate.opsForValue().get("login:user:"));
        User user = userService.getOne(wrapper);
        System.out.println(user);
        community.setUserName(user.getUsername());

        communityService.save(community);
        return community;
    }

    @GetMapping("/list")
    public List<Community> listCommunity() {
        LambdaQueryWrapper<Community> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Community::getUserId, stringRedisTemplate.opsForValue().get("login:user:"));
        System.out.println("消息列表"+communityService.list(wrapper));
        return communityService.list(wrapper);
    }
    @PostMapping("/delete/{id}")
    public List<Community> deleteCommunity(@PathVariable("id") Integer id) {
        communityService.removeById(id);
        LambdaQueryWrapper<Community> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Community::getUserId, stringRedisTemplate.opsForValue().get("login:user:"));
        return communityService.list(wrapper);
    }
}
